package com.chao.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http请求工具类
 * @author ZhouGuixing
 */
public class SysHttpUtil {

    private static Logger log = LoggerFactory.getLogger(SysHttpUtil.class);

    /**
     * 发送post请求 key-value
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Map<String,String> param){
        return doPost(url,param,null);
    }

    /**
     * 发送get请求
     * @param url
     * @param param
     * @return
     */
    public static String doGet(String url, Map<String,String> param){
        return doGet(url,param,new HashMap<>());
    }

    /**
     * 发起GET同步请求
     *
     * @param url        请求的url地址
     * @param headers    请求头参数map
     * @param parameters 请求参数map
     * @return 请求的结果字符串
     */
    public static String doGet(String url, Map<String,String> parameters, Map<String,String> headers) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //封装get请求的参数
        StringBuilder urlParameters = addGetParameters(parameters);
        HttpGet httpGet = new HttpGet(url + urlParameters);
        return getResultStr(headers, httpClient, httpGet);

    }

    /**
     * 发起POST同步请求
     *
     * @param url        请求的url地址
     * @param headers    请求头参数map
     * @param parameters 请求参数map
     * @return 请求的结果字符串
     */
    public static String doPost(String url, Map<String,String> parameters, Map<String,String> headers){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        addParameters(httpPost, parameters, null);
        return getResultStr(headers, httpClient, httpPost);
    }

    /**
     * 发送post请求 json
     * @param url
     * @return
     */
    public static String doPostJson(String url, String parameters, Map<String,String> headers,int s){
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            addParameters(httpPost, null, parameters);
            httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(s).setSocketTimeout(s).setConnectTimeout(s).build());
            return getResultStr(headers, httpClient, httpPost);
        } catch (Exception e) {
            log.error("发送postToString请求失败",e);
        }
        return null;
    }


    /**
     * 发起POST同步请求
     *
     * @param url        请求的url地址
     * @param headers    请求头参数map
     * @param parameters 请求参数map
     * @return 请求的结果字符串
     */
    public static String doPostJson(String url, String parameters, Map<String,String> headers){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        addParameters(httpPost, null, parameters);
        return getResultStr(headers, httpClient, httpPost);
    }

    /**
     * 发起设备请求
     * @param url        请求的url地址
     * @param parameters 请求参数map
     * @return 请求的结果字符串
     */
    public static String doDeviceJson(String url, String parameters){
        Map<String,String> headers = new HashMap<>();

        SocketConfig socketConfig = SocketConfig.custom()
                .setSoKeepAlive(false)
                .setSoLinger(1)
                .setSoReuseAddress(true)
                .setSoTimeout(10000)
                .setTcpNoDelay(true).build();
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(10000).setSocketTimeout(10000)
                .setConnectionRequestTimeout(10000).build();

        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setEntity(new StringEntity(parameters, StandardCharsets.UTF_8));
        return SysHttpUtil.getResultStr(headers, httpClient, httpPost);
    }

    /**
     * 添加get请求的参数
     *
     * @param parameters 请求参数的map
     * @return StringBuilder
     */
    private static StringBuilder addGetParameters(Map<String, String> parameters) {
        if(parameters.isEmpty()){
            return new StringBuilder();
        }
        StringBuilder urlParameters = new StringBuilder();
        urlParameters.append("?");
        for (String key : parameters.keySet()) {
            String value = parameters.get(key);
            urlParameters.append(key).append("=").append(value).append("&");
        }
        return urlParameters;
    }

    /**
     * 设置请求头参数
     *
     * @param headers     请求头map集合
     * @param httpRequest http请求对象
     */
    private static void setHeaders(Map<String, String> headers, HttpRequestBase httpRequest) {
        if (headers != null && !headers.isEmpty()) {
            for (String key : headers.keySet()) {
                String value = headers.get(key);
                httpRequest.setHeader(key, value);
            }
        }
    }

    /**
     * POST、GET请求的参数添加方式
     *
     * @param parameters     需要添加到请求参数的map集合
     * @param postPutRequest post或者get请求对象
     * @param jsonStr        请求json参数
     * @throws UnsupportedEncodingException 传递参数引发的异常
     */
    private static void addParameters(HttpEntityEnclosingRequestBase postPutRequest, Map<String, String> parameters, String jsonStr){
        if (!StringUtils.isEmpty(jsonStr)) {
            postPutRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
            postPutRequest.setEntity(new StringEntity(jsonStr, Charset.forName("UTF-8")));
        } else {
            // 1、构造list集合，往里面存请求的数据
            List<NameValuePair> list = new ArrayList<>();
            for (String key : parameters.keySet()) {
                String value = parameters.get(key);
                BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, value);
                list.add(basicNameValuePair);
            }
            //2 我们发现Entity是一个接口，所以只能找实现类，发现实现类又需要一个集合，集合的泛型是NameValuePair类型
            UrlEncodedFormEntity formEntity = null;
            try {
                formEntity = new UrlEncodedFormEntity(list, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //3 通过setEntity 将我们的entity对象传递过去
            postPutRequest.setEntity(formEntity);
        }

    }

    /**
     * 获取请求的返回结果字符串
     *
     * @param headers     请求头map集合
     * @param httpClient  htt请求对象
     * @param httpRequest 请求的http方式对象
     * @return 请求结果字符串
     */
    public static String getResultStr(Map<String, String> headers, CloseableHttpClient httpClient, HttpRequestBase httpRequest) {
        String body = null;
        CloseableHttpResponse response;
        //设置请求头的参数
        setHeaders(headers, httpRequest);

        try {
            //执行请求
            response = httpClient.execute(httpRequest);
            //请求成功执行
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //获取返回的数据
                HttpEntity entity = response.getEntity();
                //转换成字符串
                body = EntityUtils.toString(entity,StandardCharsets.UTF_8);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
}
